/*
 * @Author: wangqizhang
 * @Date: 2024-04-29 16:04:18
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-05-12 16:44:28
 * @FilePath: /suixinji-server/middleWare/user.mw.js
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
const bcrypt = require('bcrypt');
const { getUserInfoByUserName } = require('../service/user.service');
//密码加密
const encryptPassword = async (ctx, next) => {
  // 生成一个随机的 salt
  const salt = bcrypt.genSaltSync(10);

  // 对密码进行加密
  const hash = bcrypt.hashSync(ctx.request.body.pass_word, salt);
  ctx.request.body.pass_word = hash;
  await next();
};
//密码比对
const comparePassword = (password, hash) => {
  return bcrypt.compareSync(password, hash);
};
//用户信息校验
const validateUser = async (ctx, next) => {
  const { user_name, pass_word } = ctx.request.body;
  if (!user_name || !pass_word) {
    ctx.status = 201;
    ctx.body = {
      code: '9999',
      message: '用户名或密码不能为空',
      data: null,
    };
    return;
  }
  const res = await getUserInfoByUserName(user_name);
  if (res.status && res.result !== null) {
    ctx.status = 201;
    ctx.body = {
      code: '9999',
      message: '用户名已存在',
      data: null,
    };
    return;
  }
  await next();
};
const validHasUser = async (ctx, next) => {
  const { user_name, pass_word } = ctx.request.body;
  if (!user_name || !pass_word) {
    ctx.status = 201;
    ctx.body = {
      code: '9999',
      message: '用户名或密码不能为空！',
      data: null,
    };
    return;
  }
  const res = await getUserInfoByUserName(user_name);
  if (!res.status || res.result === null) {
    ctx.status = 201;
    ctx.body = {
      code: '9999',
      message: '用户不存在！',
      data: null,
    };
    return;
  }
  await next();
};
module.exports = {
  encryptPassword,
  comparePassword,
  validateUser,
  validHasUser,
};
